<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-4-3
 */

namespace app\admin\controller;

use think\Db;
use think\Page;

class Store extends Base
{
    public function _initialize(){
        parent::_initialize();
    }

    public function api_conf()
    {
        if (IS_AJAX_POST) {
            $data = tpSetting("OpenMinicode.conf", []);
            $data = json_decode($data, true);
            empty($data) && $data = [];

            $post = input('post.');
            if ($post['apikey'] != $post['old_apikey']) {
                $post['apikey_uptime'] = getTime();
            }
            $data = array_merge($data, $post);
            tpSetting('OpenMinicode', ['conf' => json_encode($data)]);
            $this->success("操作成功");
        }
    }

    /**
     * 重置API接口密钥
     * @return [type] [description]
     */
    public function reset_apikey()
    {
        if (IS_AJAX_POST) {
            $data = tpSetting("OpenMinicode.conf", []);
            $data = json_decode($data, true);
            empty($data) && $data = [];
            $apikey = get_rand_str(32, 0, 1);
            $data['apikey'] = $apikey;
            $this->success("重置成功", null, ['apikey'=>$apikey]);
        }
    }

    // 微信小程序
    public function weixin_conf()
    {
        if (IS_AJAX_POST) {
            $post = input('post.');
            $post['appid'] = !empty($post['appid']) ? trim($post['appid']) : '';
            $post['appsecret'] = !empty($post['appsecret']) ? trim($post['appsecret']) : '';
            $post['mchid'] = !empty($post['mchid']) ? trim($post['mchid']) : '';
            $post['apikey'] = !empty($post['apikey']) ? trim($post['apikey']) : '';

            $data = [];
            if (!empty($post['appid']) || !empty($post['appsecret'])) {
                if (empty($post['appid'])) {
                    $this->error('AppID不能为空！');
                }
                if (empty($post['appsecret'])) {
                    $this->error('AppSecret不能为空！');
                }
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$post['appid']."&secret=".$post['appsecret'];
                $response = httpRequest($url);
                $params = json_decode($response, true);
                if (!isset($params['access_token'])) {
                    $this->error('AppID或AppSecret不正确！');
                }
                $data['access_token']  = $params['access_token'];
                $data['expire_time']  = getTime() + $params['expires_in'] - 1000;

                if (!empty($post['appid']) && !empty($post['mchid']) && !empty($post['apikey'])) {
                    $logic = new \app\api\logic\v1\ApiLogic;
                    $returnData = $logic->GetWechatAppletsPay($post['appid'], $post['mchid'], $post['apikey']);
                    if (empty($returnData['code'])) {
                        $this->error($returnData['msg']);
                    }
                }
            }

            $data = array_merge($post, $data);
            tpSetting('OpenMinicode', ['conf_weixin' => json_encode($data)]);

            if (!empty($post['web'])) {
                tpCache('web', $post['web']);
            }
            $this->success("操作成功");
        }

        $data = tpSetting("OpenMinicode.conf");
        if (empty($data)) {
            $data = [];
            $data['apiopen'] = 0;
            $data['apiverify'] = 0;
            $data['apikey'] = get_rand_str(32, 0, 1);
            tpSetting('OpenMinicode', ['conf' => json_encode($data)]);
        } else {
            $data = json_decode($data, true);
        }
        $this->assign('data', $data);

        //微信信息
        $weixin_data = tpSetting("OpenMinicode.conf_weixin");
        $weixin_data = json_decode($weixin_data, true);
        $this->assign('weixin_data', $weixin_data);
        // 小程序码
        $weixin_qrcodeurl = "";
        if (!empty($weixin_data['appid'])) {
            $filepath = UPLOAD_PATH."allimg/202205/weixin-".md5($weixin_data['appid']).".png";
            if (is_file($filepath)) {
                $weixin_qrcodeurl = "{$this->root_dir}/".$filepath;
            }
        }
        $this->assign('weixin_qrcodeurl', $weixin_qrcodeurl);

        return $this->fetch();
    }

    /**
     * 获取微信小程序码
     * @return [type] [description]
     */
    public function ajax_get_weixin_qrcode()
    {
        $tokenData = getWeixinAccessToken();
        if (!empty($tokenData['code'])) {
            if (isset($tokenData['access_token'])) {
                $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$tokenData['access_token'];
                $post_data = array(
                    "scene" => 'test',
                    "width" => 280,
                );
                $response = httpRequest($url, 'POST', json_encode($post_data, JSON_UNESCAPED_UNICODE));
                $params = json_decode($response,true);
                if (is_array($params) || $response === false) {
                    $msg = !empty($params['errmsg']) ? $params['errmsg'] : '可能没发布小程序';
                    $this->error($msg);
                } else {
                    $weixin_data = tpSetting("OpenMinicode.conf_weixin");
                    if (!empty($weixin_data)) {
                        $weixin_data = json_decode($weixin_data, true);
                    }
                    $qrcodeurl = UPLOAD_PATH.'allimg/202205';
                    tp_mkdir($qrcodeurl);
                    $qrcodeurl = $qrcodeurl."/weixin-".md5($weixin_data['appid']).".png";
                    if (@file_put_contents($qrcodeurl, $response)){
                        $qrcodeurl = $this->root_dir.'/'.$qrcodeurl;
                        $this->success('生成小程序码成功', null, ['qrcodeurl'=>$qrcodeurl]);
                    } else {
                        $this->error('生成小程序码失败');
                    }
                }
            }
        }

        $this->error($params['msg']);
    }

    // 微信公众号
    public function wechat_conf()
    {
        if (IS_AJAX_POST) {
            $post = input('post.');
            $appid = trim($post['appid']);
            $appsecret = trim($post['appsecret']);

            $data = [];
            if (!empty($appid) || !empty($appsecret)) {
                if (empty($appid)) {
                    $this->error('AppID不能为空！');
                }
                if (empty($appsecret)) {
                    $this->error('AppSecret不能为空！');
                }

                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
                $response = httpRequest($url);
                $params = json_decode($response, true);
                if (!isset($params['access_token'])) {
                    $wechat_code = config('error_code.wechat');
                    $msg = !empty($wechat_code[$params['errcode']]) ? $wechat_code[$params['errcode']] : $params['errmsg'];
                    $this->error($msg);
                }

                // 公众号是否认证
                $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token={$params['access_token']}";
                $res = json_decode(httpRequest($url), true);
                if (!isset($res['total'])) {
                    $this->error('必须是已认证的服务号！');
                }

                $data['access_token']  = $params['access_token'];
                $data['expire_time']  = getTime() + $params['expires_in'] - 1000;
            }

            $data['appid']  = $appid;
            $data['appsecret'] = $appsecret;
            $data['token'] = empty($post['token']) ? get_rand_str(32, 0, 1) : trim($post['token']);
            $data['type'] = $post['type'];
            $data['wait_access'] = 1;
            tpSetting('OpenMinicode', ['conf_wechat' => json_encode($data)]);

            // 兼容老数据的功能，同步保存一份到以前配置里
            $wechat_login_config = unserialize($this->usersConfig['wechat_login_config']);
            $wechat_login_config = !empty($wechat_login_config) ? $wechat_login_config : [];
            $wechat_login_config['appid']  = $appid;
            $wechat_login_config['appsecret'] = $appsecret;
            getUsersConfigData('wechat', ['wechat_login_config'=>serialize($wechat_login_config)]);

            // 设置所属行业
            try {
                if (!empty($data['access_token'])) {
                    $post_data = [];
                    $url = "https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token=".$data['access_token'];
                    $response = httpRequest($url);
                    $params = json_decode($response, true);
                    if (is_array($params) && !empty($params)) {
                        $i = 1;
                        foreach ([1=>'IT科技-互联网|电子商务', 41=>'其他-其他'] as $key => $val) {
                            $is_exist = false;
                            foreach ($params as $_k => $_v) {
                                if ($val == ($_v['first_class'].'-'.$_v['second_class'])) {
                                    $is_exist = true;
                                }
                            }
                            if (!$is_exist) {
                                $post_data['industry_id'.$i] = $key;
                                $i++;
                            }
                        }
                    }
                    if (!empty($post_data)) {
                        $url = "https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token=".$data['access_token'];
                        httpRequest($url, 'POST', json_encode($post_data, JSON_UNESCAPED_UNICODE));
                    }
                }
            } catch (\Exception $e) {
                
            }

            $this->success("操作成功");
        }

        $data = tpSetting("OpenMinicode.conf_wechat");
        if (!empty($data)) {
            $data = json_decode($data, true);
        } else {
            $data = [];
        }
        $data['token'] = empty($data['token']) ? get_rand_str(32, 0, 1) : trim($data['token']);
        // 服务器地址(URL)
        $data['apiurl'] = request()->domain().ROOT_DIR."/index.php?s=/api/Wechat/valid";

        /*验证IP是否加入白名单中*/
        $ipTips = '';
        if (!empty($data['appid']) && !empty($data['appsecret'])) {
            $tokenData = getWechatAccessToken(true);
            if (!empty($tokenData['access_token'])) {
                // 公众号是否认证
                $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token={$tokenData['access_token']}";
                $res = json_decode(httpRequest($url), true);
                if (!isset($res['total'])) {
                    $data['type'] = 1; // 未认证
                } else {
                    $data['type'] = 2; // 已认证
                }
            }
            else if (!empty($tokenData['errcode'])) {
                if ($tokenData['errcode'] == 40164) {
                    preg_match_all('#(\d{1,3}\.){3}\d{1,3}#i', $tokenData['msg'], $matches);
                    $ip = !empty($matches[0][0]) ? $matches[0][0] : '';
                    $ipTips = "<font color='red'>请先将IP：{$ip} 加入微信公众号的IP白名单里，具体点击<a href=\"JavaScript:void(0);\" onclick=\"click_to_eyou_1575506523('https://www.eyoucms.com/plus/view.php?aid=9432','IP白名单配置教程')\">查看教程</a>！</font>";
                } else {
                    $ipTips = "<font color='red'>{$tokenData['msg']}</font>";
                }
            }
        }
        $this->assign('ipTips', $ipTips);
        /*--end*/

        $this->assign('data', $data);

        // 公众号二维码
        $wechat_qrcodeurl = "";
        if (!empty($data['appid'])) {
            $admin_id = (int)session('admin_id');
            $filepath = UPLOAD_PATH."allimg/202205/wechat-".md5('admin_id-'.$admin_id).".png";
            if (is_file($filepath)) {
                $wechat_qrcodeurl = "{$this->root_dir}/".$filepath;
            }
        }
        $this->assign('wechat_qrcodeurl', $wechat_qrcodeurl);

        return $this->fetch();
    }

    /**
     * 获取微信公众号二维码
     * @return [type] [description]
     */
    public function ajax_get_wechat_qrcode()
    {
        $tokenData = getWechatAccessToken();
        if (!empty($tokenData['code'])) {
            if (isset($tokenData['access_token'])) {
                $admin_id = (int)session('admin_id');
                $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$tokenData['access_token'];
                $post_data = array(
                    "action_name" => 'QR_LIMIT_STR_SCENE',
                    "action_info" => [
                        'scene' => [
                            'scene_str' => "{$admin_id}|eyou_admin",
                        ],
                    ],
                );
                $response = httpRequest($url, 'POST', json_encode($post_data, JSON_UNESCAPED_UNICODE));
                $params = json_decode($response,true);
                if (empty($params['ticket'])) {
                    $msg = !empty($params['errmsg']) ? $params['errmsg'] : '生成二维码失败';
                    $this->error($msg);
                } else {
                    // 调用微信接口，返回已生成二维码图片资源
                    $ticket = urlencode($params['ticket']);
                    // 调用接口获取图片资源
                    $url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . $ticket;
                    $picResponse = httpRequest($url);
                    // 将资源加载到图片并返回
                    $qrcodeurl = UPLOAD_PATH.'allimg/202205';
                    tp_mkdir($qrcodeurl);
                    $qrcodeurl = $qrcodeurl."/wechat-".md5('admin_id-'.$admin_id).".png";
                    if (@file_put_contents($qrcodeurl, $picResponse)){
                        $qrcodeurl = $this->root_dir.'/'.$qrcodeurl;
                        $this->success('生成二维码成功', null, ['qrcodeurl'=>$qrcodeurl]);
                    } else {
                        $this->error('生成二维码失败');
                    }
                }
            }
        }

        $this->error($params['msg']);
    }

    public function wechat_conf_share()
    {
        if (IS_POST) {
            $post = input('post.');
            if (isset($post['web'])) {
                $param = $post['web'];
                tpCache('web', $param);
                write_global_params(); // 写入全局内置参数
            }

            $this->success('操作成功', url('Store/m_conf'));
        }

        return $this->fetch();
    }

    public function m_conf()
    {
        if (IS_POST) {
            $post = input('post.');
            if (isset($post['web'])) {
                $param = $post['web'];
                $param['web_keywords_m'] = str_replace('，', ',', $param['web_keywords_m']);
                $param['web_description_m'] = filter_line_return($param['web_description_m']);
                // 小程序端
                $param['web_status_url_wx'] = trim($param['web_status_url_wx']);
                $web_status_tpl_wx = trim($param['web_status_tpl_wx']);
                $web_status_tpl_wx = trim($web_status_tpl_wx, '/');
                if (!empty($this->root_dir)) {
                    $web_status_tpl_wx = preg_replace('#^'.$this->root_dir.'/#i', '', '/'.$web_status_tpl_wx);
                    $web_status_tpl_wx = trim($web_status_tpl_wx, '/');
                }
                $param['web_status_tpl_wx'] = $web_status_tpl_wx;
                // 手机端
                $param['web_status_url_m'] = trim($param['web_status_url_m']);
                $web_status_tpl_m = trim($param['web_status_tpl_m']);
                $web_status_tpl_m = trim($web_status_tpl_m, '/');
                if (!empty($this->root_dir)) {
                    $web_status_tpl_m = preg_replace('#^'.$this->root_dir.'/#i', '', '/'.$web_status_tpl_m);
                    $web_status_tpl_m = trim($web_status_tpl_m, '/');
                }
                $param['web_status_tpl_m'] = $web_status_tpl_m;

                if (1 == $param['web_status_m']) {
                    @unlink('./index.html');
                }

                /*EyouCMS安装目录*/
                empty($param['web_cmspath']) && $param['web_cmspath'] = $this->root_dir; // 支持子目录
                $web_cmspath = trim($param['web_cmspath'], '/');
                $web_cmspath = !empty($web_cmspath) ? '/'.$web_cmspath : '';
                $param['web_cmspath'] = $web_cmspath;

                // 网站根网址
                $web_basehost = rtrim($param['web_basehost'], '/');
                if (!is_http_url($web_basehost) && !empty($web_basehost)) {
                    $web_basehost = $this->request->scheme().'://'.$web_basehost;
                }
                $param['web_basehost'] = $web_basehost;

                tpCache('web', $param);
                write_global_params(); // 写入全局内置参数
            }

            $this->success('操作成功', url('Store/m_conf'));
        }

        return $this->fetch();
    }

    public function pc_conf()
    {
        if (IS_POST) {
            $post = input('post.');
            if (isset($post['web'])) {
                $param = $post['web'];
                $param['web_keywords'] = str_replace('，', ',', $param['web_keywords']);
                $param['web_description'] = filter_line_return($param['web_description']);
                $param['web_status_url'] = trim($param['web_status_url']);
                $web_status_tpl = trim($param['web_status_tpl']);
                $web_status_tpl = trim($web_status_tpl, '/');
                if (!empty($this->root_dir)) {
                    $web_status_tpl = preg_replace('#^'.$this->root_dir.'/#i', '', '/'.$web_status_tpl);
                    $web_status_tpl = trim($web_status_tpl, '/');
                }
                $param['web_status_tpl'] = $web_status_tpl;

                if (1 == $param['web_status']) {
                    @unlink('./index.html');
                }

                /*EyouCMS安装目录*/
                empty($param['web_cmspath']) && $param['web_cmspath'] = $this->root_dir; // 支持子目录
                $web_cmspath = trim($param['web_cmspath'], '/');
                $web_cmspath = !empty($web_cmspath) ? '/'.$web_cmspath : '';
                $param['web_cmspath'] = $web_cmspath;

                // 网站根网址
                $web_basehost = rtrim($param['web_basehost'], '/');
                empty($web_basehost) && $web_basehost = request()->host(true);
                if (!is_http_url($web_basehost) && !empty($web_basehost)) {
                    $web_basehost = $this->request->scheme().'://'.$web_basehost;
                }
                $param['web_basehost'] = $web_basehost;

                tpCache('web', $param);
                write_global_params(); // 写入全局内置参数
            }

            $this->success('操作成功', url('Store/pc_conf'));
        }

        return $this->fetch();
    }
}